package webstart;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.util.logging.Logger;

public class DataViewUtil {
	private static Logger log = Logger.getLogger(DataViewUtil.class.getName());

	public static byte[] writeObject(Object object) {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		byte[] ab = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			ab = baos.toByteArray();
		} catch (IOException e) {
			log.severe("convert object to byte array error:" + e);
			return null;
		} finally {
			try {
				if (oos != null)
					oos.close();
				if(baos!=null)
					baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return ab;
	}

	public static Object readObject(InputStream inputStream) {
		Object o = null;
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(inputStream);
			o = ois.readObject();
		} catch (Exception e) {
			log.severe("convert stream to object error: " + e);
		}finally {
			if (ois != null)
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.severe("" + e);
				}
		}
		return o;
	}

	public static URLConnection getCon(String path) {
		java.net.URLConnection con = null;
		try {
			java.net.URL url = new java.net.URL(path);
			con = url.openConnection();
			con.setUseCaches(true);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-type", "application/octest-stream");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.severe("" + e);
		}
		return con;
	}
	
	public static void writeObject(OutputStream outStream, Object writeObj) throws IOException {
		if (writeObj != null) {
			DataOutputStream dataout = new DataOutputStream(outStream);
			byte[] buf = writeObject(writeObj);
			dataout.write(buf);
			dataout.flush();
			dataout.close();
		}
	}

	public static Object parseObject(String path, Object writeObj) throws Exception {
		Object readObj = null;
		URLConnection con = getCon(path);
		try {
			writeObject(con.getOutputStream(), writeObj);

			DataInputStream in = new DataInputStream(con.getInputStream());
			readObj = readObject(in);
			in.close();
		} catch (Exception e) {
			log.severe("" + e);
			throw new Exception(e);
		}
		return readObj;
	}
}
